package com.nio.controller;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousFileChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.Future;

public class AsynchronousFileChannelDemo {
    public static void main(String[] args) {
        Path path = Paths.get("F:\\niotest\\3.txt");
        AsynchronousFileChannel asynchronousFileChannel = null;
        try {
            asynchronousFileChannel = AsynchronousFileChannel.open(path, StandardOpenOption.READ);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 创建buffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        long positon = 0;
        // 调用channel的read方法得到true
        Future<Integer> read = asynchronousFileChannel.read(byteBuffer, positon);
        // 判断操作是否完成isDone,返回true
        while (!read.isDone());
        // 切换读写模式
        byteBuffer.flip();
        // byteBuffer.limit() buffer的大小
        byte[] bytes = new byte[byteBuffer.limit()];
        byteBuffer.get(bytes);
        System.out.println(new String(bytes));
        byteBuffer.clear();
    }
}
